package cn.edu.swu.mhans.room.bean.factory;

import cn.edu.swu.mhans.room.bean.RoomBeanDefinition;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * bean工厂的抽象实现，使用模板模式对bean工厂的设计予以规范
 *
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2018/3/26
 */
@Data
public abstract class AbstractRoomBeanFactory implements RoomBeanFactory {

    private Map<String, RoomBeanDefinition> registerMap = new HashMap<>();

    private Map<String, Object> roomBeanMap = new HashMap<>();

    /**
     * 获取一个对象实例
     *
     * @param roomBeanName bean的名称
     * @return 对象实例
     * @throws Exception 异常
     */
    @Override
    public Object getRoomBean(String roomBeanName) throws Exception {
        RoomBeanDefinition roomBeanDefinition = registerMap.get(roomBeanName);
        if (null == roomBeanDefinition) {
            throw new IllegalArgumentException("no bean named " + roomBeanName);
        }
        Object bean = roomBeanMap.get(roomBeanName);
        if (null == bean) {
            bean = doCreateRoomBean(roomBeanDefinition);
            roomBeanMap.put(roomBeanName, bean);
        }
        return bean;
    }

    /**
     * 实例化RoomBean，子类实现
     *
     * @param roomBeanDefinition bean的描述
     * @return 实例化的对象
     * @throws Exception 反射过程中出现的异常
     */
    protected abstract Object doCreateRoomBean(RoomBeanDefinition roomBeanDefinition) throws Exception;


    @Override
    public void registerRoomBeanDefinition(String name, RoomBeanDefinition roomBeanDefinition) {
        registerMap.put(name, roomBeanDefinition);
    }

}
